package ferus.tigris.lines.levels;

import java.util.Random;

import ferus.tigris.lines.GameManager;
import ferus.tigris.lines.Matrix;
import ferus.tigris.lines.Builders.AbstractBehaviorBuilder;
import ferus.tigris.lines.Builders.BuilderWith7Builders;
import ferus.tigris.lines.Builders.BuilderWith8Builders;
import ferus.tigris.lines.personages.AbstractBehavior;

public class LevelWithNullAndRandomInit extends StaticLevel {
	private GameManager gameManager;
	private LevelManager levelManager;
	public LevelWithNullAndRandomInit(LevelManager levelManager, GameManager gameManager, int scope, int complexity) {
		super(levelManager, gameManager, scope, complexity);
		this.gameManager = gameManager;
		this.levelManager = levelManager;
	}

	public AbstractLevel nextLevel() {
		if(complexity() < 120) {
			changeBuilder(new BuilderWith7Builders());
		} else {
			changeBuilder(new BuilderWith8Builders());
		}
		return new LevelWithRandomInit(levelManager, gameManager, complexity(), getNextComplexity());
	}

	public AbstractLevel clone() {
		return new LevelWithNullAndRandomInit(levelManager, gameManager, initScope(), complexity());
	}

	public void start() {
		super.start();
		Matrix m = marks();
		
		Random rnd = new Random();
		int x1 = rnd.nextInt(m.columns()/2), x2 = 0;
		int y1 = rnd.nextInt(m.rows()/2), y2 = 0;
		
		do {
			x2 = rnd.nextInt(m.columns()/2);
			y2 = rnd.nextInt(m.rows()/2);
		} while((x1 == x2)||(y1 == y2));

		AbstractBehaviorBuilder builder = new AbstractBehaviorBuilder();

		AddRandomMark(builder, x1, y1);
		AddRandomMark(builder, x1, m.rows() - y1 - 1);
		AddRandomMark(builder, m.columns() - x1 - 1, y1);
		AddRandomMark(builder, m.columns() - x1 - 1, m.rows() - y1 - 1);

		AddNullMark(builder, x2, y2);
		AddNullMark(builder, x2, m.rows() - y2 - 1);
		AddNullMark(builder, m.columns() - x2 - 1, y2);
		AddNullMark(builder, m.columns() - x2 - 1, m.rows() - y2 - 1);
	}

	protected void AddNullMark(AbstractBehaviorBuilder builder, int x, int y) {
		Matrix m = marks();
		AbstractBehavior mark = builder.createNull();
		m.insertMark(x, y, mark);
	}

	protected void AddRandomMark(AbstractBehaviorBuilder builder, int x, int y) {
		Matrix m = marks();
		AbstractBehavior mark = builder.createRandomMark(gameManager.view());
		m.insertMark(x, y, mark);
	}

}
